from TextBadger.models import *
from xml.dom.minidom import parse
from django.conf import settings
import sys

codebooks = Codebook.objects.filter(status=2)

for codebook in codebooks:
	codebook.status=3
	codebook.save()

for codebook in codebooks:
	print codebook.id
	xmlfile = codebook.codebook_file.path
	dom = parse(xmlfile)
	try:
		nques = int(dom.getElementsByTagName("questions")[0].attributes['num_ques'].value)
	except:
		nques = -1
	
	try:
		questions = dom.getElementsByTagName("questions")[0].getElementsByTagName("question")
		for question in questions:
			type = question.attributes['type'].value
			ques_text = question.getElementsByTagName("text")[0].childNodes[0].data
			if type == 'mcq':
				multiple = question.attributes['multiple'].value
				if multiple == "true":
					quesobj = Codebook_Question(codebook=codebook, question_type=3, question_text=ques_text)		
				else:
					quesobj = Codebook_Question(codebook=codebook, question_type=2, question_text=ques_text)
				quesobj.save()

				# creating choices
				ques_choices = question.getElementsByTagName("choice")
				for choice in ques_choices:
					quesobj.Choices.create(text=choice.childNodes[0].data)
			else:
				# create a question
				quesobj = Codebook_Question(codebook=codebook, question_type=1, question_text=ques_text)
				quesobj.save()

		codebook.status = 1
		codebook.save()	
	except:
		print sys.exc_type, ":", sys.exc_value
		print 'File Error. Marking this codebook as invalid'
		codebook.status = 4
		codebook.save()

	
